//
//  YSSessionListViewController.m
//  YouSheng
//
//  Created by aaa on 16/8/18.
//  Copyright © 2016年 FanShuHan. All rights reserved.
//

#import "YSSessionListViewController.h"
#import "UIView+YS.h"
#import "YSSessionViewController.h"
#import "YSPersonalCardViewController.h"
#import "YSPresentationController.h"

#define SessionListTitle @"聊天"

@interface YSSessionListViewController()<NIMLoginManagerDelegate,UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning>
@property (nonatomic,strong) UILabel *titleLabel;

@property (nonatomic, strong) UIButton *coverButton;
@property (nonatomic, assign) BOOL isPresented;
@end
@implementation YSSessionListViewController
- (UIButton *)coverButton {
    if (!_coverButton) {
        _coverButton = [[UIButton alloc] init];
    }
    return _coverButton;
}

- (void)dealloc{
    [[NIMSDK sharedSDK].loginManager removeDelegate:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NIMSDK sharedSDK].loginManager addDelegate:self];
    
    [self setupNav];
    
    NSString *userID = [[[NIMSDK sharedSDK] loginManager] currentAccount];
    self.navigationItem.titleView  = [self titleView:userID];
}

/**
 *  选中某一条最近会话时触发的事件回调
 *  默认将进入会话界面
 *
 *  @param recent    最近会话
 *  @param indexPath 最近会话cell所在的位置
 */
- (void)onSelectedRecent:(NIMRecentSession *)recent atIndexPath:(NSIndexPath *)indexPath{
    YSLog(@"%@",recent);
//    YSSessionViewController *vc = [[YSSessionViewController alloc] initWithSession:recent.session];
//    [self.navigationController pushViewController:vc animated:YES];
}

/**
 *  选中某一条最近会话的头像控件，触发的事件回调
 *
 *  @param recent    最近会话
 *  @param indexPath 最近会话cell所在的位置
 */
- (void)onSelectedAvatar:(NIMRecentSession *)recent
             atIndexPath:(NSIndexPath *)indexPath{
    if (recent.session.sessionType == NIMSessionTypeP2P) {
//        YSPersonalCardViewController *vc = [[YSPersonalCardViewController alloc] initWithUserId:recent.session.sessionId];
        YSPersonalCardViewController *vc = [[YSPersonalCardViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

/**
 *  删除某一条最近会话时触发的事件回调
 *  默认将删除会话，并检查是否需要删除服务器的会话（防止漫游）
 *
 *  @param recent    最近会话
 *  @param indexPath 最近会话cell所在的位置
 */
- (void)onDeleteRecentAtIndexPath:(NIMRecentSession *)recent atIndexPath:(NSIndexPath *)indexPath{
    [super onDeleteRecentAtIndexPath:recent atIndexPath:indexPath];
//    self.emptyTipLabel.hidden = self.recentSessions.count;
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self refreshSubview];
}

#pragma mark - Private 
- (void)refreshSubview{
    [self.titleLabel sizeToFit];
    self.titleLabel.centerX   = self.navigationItem.titleView.width * .5f;
//    self.tableView.top = self.header.height;
    self.tableView.height = self.view.height - self.tableView.top;
//    self.header.bottom    = self.tableView.top + self.tableView.contentInset.top;
//    self.emptyTipLabel.centerX = self.view.width * .5f;
//    self.emptyTipLabel.centerY = self.tableView.height * .5f;
}

/**
 *  cell显示的最近会话具体内容
 *  默认实现为：显示最近一条消息的内容，文本消息则显示文本信息
 *  其他类型消息详见本类中 - (NSString*)messageContent:(NIMMessage *)lastMessage 方法的实现。
 *
 *  @param  recent  最近会话
 *  @return 具体内容名
 */
- (NSString *)contentForRecentSession:(NIMRecentSession *)recent {
    return [super contentForRecentSession:recent];
}

- (UIView*)titleView:(NSString*)userID{
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    self.titleLabel.text =  SessionListTitle;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:15.f];
    [self.titleLabel sizeToFit];
    UILabel *subLabel  = [[UILabel alloc] initWithFrame:CGRectZero];
    subLabel.textColor = [UIColor grayColor];
    subLabel.font = [UIFont systemFontOfSize:12.f];
    subLabel.text = userID;
    subLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [subLabel sizeToFit];
    
    UIView *titleView = [[UIView alloc] init];
    titleView.width  = subLabel.width;
    titleView.height = self.titleLabel.height + subLabel.height;
    
    subLabel.bottom = titleView.height;
    [titleView addSubview:self.titleLabel];
    [titleView addSubview:subLabel];
    return titleView;
}

- (void)setupNav {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"加号" style:UIBarButtonItemStyleDone target:self action:@selector(add:)];
}

- (void)add:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"YSPopver" bundle:nil];
    UIViewController *vc = [sb instantiateInitialViewController];
    vc.transitioningDelegate = self;
    vc.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:vc animated:YES completion:nil];
}



#pragma mark - UIViewControllerTransitioningDelegate
/// 该代理方法用于返回负责转场的控制器对象
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source {
    return [[YSPresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
}

/// 该代理方法用于告诉系统谁来负责控制器如何弹出
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    _isPresented = YES;
    return self;
}

/// 该代理方法用于告诉系统谁来负责控制器如何消失
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    _isPresented = NO;
    return self;
}

/// 用于返回动画的时长, 默认用不上
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 1.0;
}

// 系统调用该方法时会传递一个transitionContext参数, 该参数中包含了我们所有需要的值
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    if (_isPresented) {
        [self animatePresentedController:transitionContext];
    } else{
        [self animateDismissedController:transitionContext];
    }
}

/// 弹出动画
- (void)animatePresentedController:(id<UIViewControllerContextTransitioning>)transitionContext {
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    [[transitionContext containerView] addSubview:toView];
    toView.transform = CGAffineTransformMakeScale(1.0, 0.0);
    toView.layer.anchorPoint = CGPointMake(0.5, 0);
    [UIView animateWithDuration:duration animations:^{
        toView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
    
}

/// 隐藏动画
- (void)animateDismissedController:(id<UIViewControllerContextTransitioning>)transitionContext {
    NSTimeInterval duration = [self transitionDuration:transitionContext];
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    [UIView animateWithDuration:duration animations:^{
        fromView.transform = CGAffineTransformMakeScale(1.0, 0.0001);
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}
@end
